package com.liuyucheng.idea_springboot.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class IOUtil {
	/**
	 * 将文件转换为字节数组
	 * @param path 文件路径
	 * @return
	 * @throws IOException
	 */
	public static byte[] getFileByte(String path) throws IOException{
		InputStream in = new FileInputStream(new File(path));
		return read(in);
	}
	
	/**
	 * 将输入流转换为字节数组
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] read(InputStream inputStream) throws IOException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num = inputStream.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = inputStream.read(buffer);
            }
            baos.flush();
            return baos.toByteArray();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
	
	/**
	 * 写出到文件
	 * @param arr 字节数组
	 * @param path 文件完整路径
	 * @throws IOException
	 */
	public static void writeFile(byte[] arr,String path) throws IOException {
		FileOutputStream fos = new FileOutputStream(path);
		fos.write(arr);
		fos.close();
	}
}









